package com.leinao.media.runner;

import cn.hutool.core.collection.CollUtil;
import com.leinao.media.constants.MediaConstant;
import com.leinao.media.entity.LogoutParam;
import com.leinao.media.service.MediaService;
import com.leinao.media.service.RedisService;
import com.leinao.media.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Collection;

/**
 * 项目关闭时执行
 *
 * @author zhangyu
 * @date 2021/12/21 14:57
 */
@Component
public class CloseProject {

    private static final Logger logger = LoggerFactory.getLogger(CloseProject.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private MediaService mediaService;

    @Value("${sdk.enable.hk:true}")
    private boolean enableHk;

    @Value("${sdk.enable.dh:true}")
    private boolean enableDh;

    @PreDestroy
    public void destroy() throws Exception {
        logger.info("-----------destroy-----------");
        Collection<String> keys = redisService.keys(MediaConstant.NVR_CACHE_PREFIX + "*");
        if (CollUtil.isNotEmpty(keys)) {
            keys.forEach(key -> {
                Object uid = redisService.getCacheObject(key);
                if (null == uid) {
                    return;
                }
                int type;
                // 登出参数
                LogoutParam param = new LogoutParam();
                // 海康
                if (uid instanceof Integer) {
                    type = MediaConstant.NVR_TYPE_HK;
                    // 登出
                    param.setUid((int) uid);
                } else {
                    // 大华
                    type = MediaConstant.NVR_TYPE_DH;
                    param.setUid((long) uid);
                    // 登出
                }
                param.setType(type);
                mediaService.logout(param);
            });
            // 删除redis记录
            redisService.deleteObject(redisService.keys(MediaConstant.NVR_CACHE_PREFIX + "*"));
        }
        // 释放SDK资源
        int type = CommonUtils.getSdkEnableType(enableHk, enableDh);
        mediaService.cleanup(type);
    }

}
